﻿using FreeSql;
using NPOI.SS.Formula.Functions;
using Publicuse.Entity;
using Publicuse.Entity.sqlsugar;
using Publicuse.Interface;
using Publicuse.Util;
using ServiceStack.Script;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace Publicuse.Service
{
    public class BaseFreeSqlService : IBaseFreeSqlService
    {
        protected IFreeSql freeSql;

        public BaseFreeSqlService(IFreeSql freeSql)
        {
            this.freeSql = freeSql;
        }

        /// <summary>
        /// 执行任务
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="msg"></param>
        /// <param name="action"></param>
        /// <param name="istran"></param>
        /// <returns></returns>
        private T DoTask<T>(out string msg, Func<T> action, bool istran = false)
        {
            msg = string.Empty;
            T result = default(T);
            if (istran)
            {
                using (var uow = this.freeSql.CreateUnitOfWork())
                {
                    try
                    {
                        result = action.Invoke();
                        uow.Commit();
                    }
                    catch (Exception ex)
                    {
                        msg = ex.Message;
                        if (ex.InnerException != null)
                        {
                            msg += "," + ex.InnerException.Message;
                        }
                        uow.Rollback();
                    }
                }
            }
            else
            {
                result = action.Invoke();
            }
            return result;
        }

        #region 查询 
        /// <summary>
        /// 查询所有的数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="msg"></param>
        /// <returns></returns>
        public List<T> GetAll<T>(out string msg) where T : class, new()
        {
            return this.DoTask<List<T>>(out msg, () =>
            {
                return this.freeSql.Queryable<T>().ToList();
            }, false);
        }

        /// <summary>
        /// 根据SQL查询数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public List<T> QueryBySql<T>(string sql, out string msg) where T : class, new()
        {
            return this.DoTask<List<T>>(out msg, () =>
            {
                return this.freeSql.Select<T>().WithSql(sql).ToList();
            }, false);
        }

        /// <summary>
        /// 根据SQL查询数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public List<T> Query<T>(string sql, out string msg) where T : class, new()
        {
            return this.DoTask<List<T>>(out msg, () =>
            {
                return this.freeSql.Select<T>().WithSql(sql).ToList();
            }, false);
        }

        /// <summary>
        /// 根据SQL查询数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parameter"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public List<T> Query<T>(string sql, object parameter, out string msg) where T : class, new()
        {
            return this.DoTask<List<T>>(out msg, () =>
            {
                return this.freeSql.Select<T>().WithSql(sql).ToList();
            }, false);
        }

        /// <summary>
        /// 根据SQL传递参数查询数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sql"></param>
        /// <param name="parameter"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public List<T> QueryBySqlPara<T>(string sql, object parameter, out string msg) where T : class, new()
        {
            return this.DoTask<List<T>>(out msg, () =>
            {
                var data = this.freeSql.Ado.Query<T>(sql, parameter).ToList();
                return data;
            }, false);
        }

        /// <summary>
        /// 根据条件查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="expression"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public List<T> QueryByExpression<T>(Expression<Func<T, bool>> expression, out string msg) where T : class, new()
        {
            return this.DoTask<List<T>>(out msg, () =>
            {
                return this.freeSql.Queryable<T>().Where(expression).ToList();
            }, false);
        }

        /// <summary>
        /// 通过编号查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public T FindById<T>(int id, out string msg) where T : class, new()
        {
            return this.DoTask<T>(out msg, () =>
            {
                var tableName = TableAtributeUtil.GetTable<T>();
                return this.freeSql.Ado.QuerySingle<T>($"select * from {tableName} where Id = @id", new { id = 1 });
            }, false);
        }

        /// <summary>
        /// 通过编号查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <param name="msg"></param>
        /// <param name="entity"></param>
        public void QueryInfoByID<T>(int id, out string msg, out T entity) where T : class, new()
        {
            entity = default(T);
            entity = this.DoTask<T>(out msg, () =>
            {
                var tableName = TableAtributeUtil.GetTable<T>();
                return this.freeSql.Ado.QuerySingle<T>($"select * from {tableName} where Id = @id", new { id = 1 });
            }, false);

        }

        /// <summary>
        /// 根据条件查询
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public T FindByExpression<T>(Expression<Func<T, bool>> expression, out string msg) where T : class, new()
        {
            return this.DoTask<T>(out msg, () =>
            {
                return this.freeSql.Queryable<T>().Where(expression).First();
            }, false);
        }

        /// <summary>
        /// 根据sql获取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="msg"></param>
        /// <param name="parameters"></param>
        /// var parameters = new List<SugarParameter>(){
        /// new SugarParameter("@id",30) };
        /// <returns></returns>
        public DataTable GetDataTable(string sql, out string msg, object parameters)
        {
            return this.DoTask<DataTable>(out msg, () =>
            {
                DataTable dataTable = new DataTable();
                dataTable = this.freeSql.Select<object>().WithSql(sql).ToDataTable();
                return dataTable;
            }, false);
        }

        /// <summary>
        /// 根据sql获取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public DataTable GetDataTable(string sql, object parameters, out string msg)
        {
            return this.DoTask<DataTable>(out msg, () =>
            {
                DataTable dataTable = new DataTable();
                dataTable = this.freeSql.Select<object>().WithSql(sql, parameters).ToDataTable("*");
                return dataTable;
            }, false);
        }

        /// <summary>
        /// 根据sql获取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="msg"></param>
        /// <param name="parameters"></param>
        /// var parameters = new List<SugarParameter>(){
        /// new SugarParameter("@id",30) };
        /// <returns></returns>
        public DataSet GetDataSet(string sql, out string msg, object parameters)
        {
            return this.DoTask<DataSet>(out msg, () =>
            {
                DataSet dataSet = new DataSet();
                foreach (var item in sql.Split(';'))
                {
                    var dataTable = this.freeSql.Select<object>().WithSql(item).ToDataTable("*");
                    dataSet.Tables.Add(dataTable);
                }
                return dataSet;
            }, false);
        }

        /// <summary>
        /// 根据sql获取数据
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public DataSet GetDataSet(string sql, object parameters, out string msg)
        {
            return this.DoTask<DataSet>(out msg, () =>
            {
                DataSet dataSet = new DataSet();
                foreach (var item in sql.Split(';'))
                {
                    var dataTable = this.freeSql.Select<object>().WithSql(item).ToDataTable("*");
                    dataSet.Tables.Add(dataTable);
                }
                return dataSet;
            }, false);
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="expression"></param>
        /// <param name="orderfile"></param>
        /// <param name="orderByType"></param>
        /// <param name="totalCount"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public List<T> GetPageList<T>(int pageIndex, int pageSize, Expression<Func<T, bool>> expression, Expression<Func<T, object>> orderfile, OrderByType orderByType, out long totalCount, out string msg) where T : class, new()
        {
            msg = string.Empty;
            totalCount = 0;
            long totalCountb = 0;
            var result = this.DoTask<List<T>>(out msg, () =>
            {
                if (expression == null)
                {
                    expression = (o => true);
                }
                if(orderByType== OrderByType.Asc)
                {
                    return this.freeSql.Queryable<T>().Where(expression).Count(out totalCountb).OrderBy(orderfile).Page(pageIndex, pageSize).ToList();
                }
                if (orderByType == OrderByType.Desc)
                {
                    return this.freeSql.Queryable<T>().Where(expression).Count(out totalCountb).OrderByDescending(orderfile).Page(pageIndex, pageSize).ToList();
                }
                return new List<T>();
            }, false);
            totalCount = totalCountb;
            return result;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="msg"></param>
        /// <param name="list"></param>
        /// <param name="totalCount"></param>
        public List<T> GetPageListByProc<T>(CommonQuery query, out string msg, out List<T> list, out long totalCount) where T : class, new()
        {
            msg = string.Empty;
            list = new List<T>();
            totalCount = 0;
            var totalCountb = 0;
            list = this.DoTask<List<T>>(out msg, () =>
            {
                var p_total_where_sql = string.Empty;
                if (query.sqlWhere.Contains("|"))
                {
                    p_total_where_sql = query.sqlWhere.Split('|')[0];
                    query.sqlWhere = query.sqlWhere.Replace("|", " ");
                }
                else
                {
                    p_total_where_sql = query.sqlWhere;
                }
                DbParameter ReturnV = null;
                var list=this.freeSql.Ado.CommandFluent(query.storedProcedureName).CommandType(CommandType.StoredProcedure).CommandTimeout(60)
                .WithParameter("p_table_name", query.tableName)
                .WithParameter("p_files", query.files)
                .WithParameter("p_curr_page", query.pageIndex)
                .WithParameter("p_page_size", query.pageSize)
                .WithParameter("p_order_string", "order by " + query.sortFile)
                .WithParameter("p_ordertype_string", query.sortType)
                .WithParameter("p_total_where_string", p_total_where_sql)
                .WithParameter("p_where_string", query.sqlWhere)
                .WithParameter("p_total_rows", null, p =>
                {
                    ReturnV = p;
                    p.DbType = System.Data.DbType.Int32;
                    p.Direction = ParameterDirection.Output;
                })
                .Query<T>();
                if (!string.IsNullOrEmpty(ReturnV.Value.ToString()))
                {
                    totalCountb = (int)ReturnV.Value;
                }
                else
                {
                    totalCountb = 0;
                }
                return list;
            }, false);
            totalCount = totalCountb;
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="msg"></param>
        /// <param name="list"></param>
        /// <param name="totalCount"></param>
        public List<T> GetPageListBySql<T>(CommonQuery query, out string msg, out List<T> list, out long totalCount) where T : class, new()
        {
            msg = string.Empty;
            list = new List<T>();
            totalCount = 0;
            long totalCountb = 0;
            list = this.DoTask<List<T>>(out msg, () =>
            {
                var sql = $"select {query.files} from {query.tableName} {query.sqlWhere}  order by {query.sortFile} {query.sortType}";
                var list = this.freeSql.Select<T>().WithSql(sql).Count(out totalCountb).Page(query.pageIndex, query.pageSize).ToList();
                return list;
            }, false);
            totalCount = totalCountb;
            return list;
        }

        /// <summary>
        /// 分页查询
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="query"></param>
        /// <param name="msg"></param>
        /// <param name="list"></param>
        /// <param name="totalCount"></param>
        /// <returns></returns>
        public List<T> GetList<T>(CommonQuery query, out string msg, out List<T> list, out long totalCount) where T : class, new()
        {
            msg = string.Empty;
            list = new List<T>();
            totalCount = 0;
            long totalCountb = 0;
            list = this.DoTask<List<T>>(out msg, () =>
            {
                var sql = $"select {query.files} from {query.tableName} {query.sqlWhere}  order by {query.sortFile} {query.sortType}";
                var list = this.freeSql.Select<T>().WithSql(sql).Count(out totalCountb).Page(query.pageIndex, query.pageSize).ToList();
                return list;
            }, false);
            totalCount = totalCountb;
            return list;
        }
        #endregion

        #region 增加 
        /// <summary>
        /// 字典插入
        /// 不能写实体中的属性名，必须和数据库保持一致
        /// </summary>
        /// <param name="keyValuePairs"></param>
        /// <param name="msg"></param>
        /// <param name="aliasname"></param>
        /// <returns></returns>
        public int InsertDictionary(Dictionary<string, object> keyValuePairs, out string msg, string aliasname)
        {
            return this.DoTask<int>(out msg, () =>
            {
                return this.freeSql.InsertDict(keyValuePairs).AsTable(aliasname).ExecuteAffrows();
            }, true);
        }

        /// <summary>
        /// 匿名对象插入
        /// </summary>
        /// <param name="ob"></param>
        /// <param name="msg"></param>
        /// <param name="aliasname"></param>
        /// <returns></returns>
        public int InsertAnonyobject(object ob, out string msg, string aliasname)
        {
            return this.DoTask<int>(out msg, () =>
            {
                return -1;
            }, true);
        }


        /// <summary>
        /// 插入Guid主键自动赋值
        /// 只要设置为主键，并且C#类型是Guid 只要不传值，会自动赋值 
        /// 注意只能用： ExecuteCommand 方法不能用自增列的方法
        /// [SugarColumn(IsPrimaryKey = true)]
        /// public Guid uId { get; set; }
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public long InsertGuid<T>(T t, out string msg) where T : class, new()
        {
            return this.DoTask<long>(out msg, () =>
            {
                return this.freeSql.Insert<T>(t).ExecuteIdentity();
            }, true);
        }

        /// <summary>
        /// 增加实体 
        /// </summary>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public T InsertBackModel<T>(T t, out string msg) where T : class, new()
        {
            return this.DoTask<T>(out msg, () =>
            {
                return this.freeSql.Insert<T>(t).ExecuteInserted().FirstOrDefault();
            }, true);
        }

        /// <summary>
        /// 增加实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public long InserBackId<T>(T t, out string msg) where T : class, new()
        {
            return this.DoTask<long>(out msg, () =>
            {
                return this.freeSql.Insert<T>(t).ExecuteIdentity();
            }, true);
        }

        /// <summary>
        /// 增加实体
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public long Insert<T>(T t, out string msg) where T : class, new()
        {
            return this.DoTask<long>(out msg, () =>
            {
                return this.freeSql.Insert<T>(t).ExecuteIdentity();
            }, true);
        }

        /// <summary>
        //使用参数化内部分页插入
        //优点：500条以下速度最快，兼容所有类型和emoji，10万以上的大数据也能跑，就是慢些，内部分批量处理过了。
        //缺点：500以上就开始慢了，要加事务才能回滚 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int InsertUseParameter<T>(List<T> t, out string msg) where T : class, new()
        {
            return this.DoTask<int>(out msg, () =>
            {
                return 0;
            }, true);
        }

        /// <summary>
        /// 大数据写入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="pageSize"></param>
        /// <param name="msg"></param>
        public int InsertBulkCopy<T>(List<T> t, out string msg) where T : class, new()
        {
           return this.DoTask<int>(out msg, () =>
            {
                this.freeSql.Insert<T>(t).ExecuteMySqlBulkCopy();
                return 1;
            }, true);
        }

        /// <summary>
        /// 分页插入
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="pageSize"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int InsertPage<T>(List<T> t, int pageSize, out string msg) where T : class, new()
        {
            return this.DoTask<int>(out msg, () =>
            {
                return 1;
            }, true);
        }

        /// <summary>
        /// 不插入指定字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public long InsertIgnoreColumns<T>(T t, out string msg, params string[] columns) where T : class, new()
        {
            return this.DoTask<long>(out msg, () =>
            {
                return this.freeSql.Insert<T>(t).IgnoreColumns(columns).ExecuteIdentity();
            }, true);
        }

        /// <summary>
        /// 不插入指定字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public long InsertIgnoreColumns<T>(T t, out string msg, Expression<Func<T, object>> columns) where T : class, new()
        {
            return this.DoTask<long>(out msg, () =>
            {
                return this.freeSql.Insert<T>(t).IgnoreColumns(columns).ExecuteIdentity();
            }, true);
        }

        /// <summary>
        /// 只插入指定字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public long InsertInsertColumns<T>(T t, out string msg, params string[] columns) where T : class, new()
        {
            return this.DoTask<long>(out msg, () =>
            {
                return this.freeSql.Insert<T>(t).InsertColumns(columns).ExecuteIdentity();
            }, true);
        }

        /// <summary>
        /// 只插入指定字段
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public long InsertInsertColumns<T>(T t, out string msg, Expression<Func<T, object>> columns) where T : class, new()
        {
            return this.DoTask<long>(out msg, () =>
            {
                return this.freeSql.Insert<T>(t).InsertColumns(columns).ExecuteIdentity();
            }, true);
        }

        /// <summary>
        /// 批量添加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public List<T> InsertBatch<T>(List<T> list, out string msg) where T : class, new()
        {
            return this.DoTask<List<T>>(out msg, () =>
            {
                var result = this.freeSql.Insert<T>(list).ExecuteAffrows();
                return result as List<T>;
            }, true);
        }

        public List<T> Insert<T>(List<T> list, out string msg) where T : class, new()
        {
            return this.DoTask<List<T>>(out msg, () =>
            {
                var result = this.freeSql.Insert<T>(list).ExecuteAffrows();
                return result as List<T>;
            }, true);
        }
        #endregion

        #region 修改
        /// <summary>
        /// 根据字典更新
        /// this.sugarClient.Updateable(keyValuePairs).AS(aliasname).WhereColumns("id").ExecuteCommand();
        /// </summary>
        /// <param name="keyValuePairs"></param>
        /// <param name="msg"></param>
        /// <param name="aliasname"></param>
        /// <param name="wherename"></param>
        /// <returns></returns>
        public int UpdateDictionary(Dictionary<string, object> keyValuePairs, out string msg, string aliasname, string wherename)
        {
            return this.DoTask<int>(out msg, () =>
            {
                return this.freeSql.UpdateDict(keyValuePairs).AsTable(aliasname).WherePrimary(wherename).ExecuteAffrows();
            }, true);

        }

        /// <summary>
        /// 忽略某一列不更新
        /// this.sugarClient.Updateable(t).IgnoreColumns(it => new{ it.CreateTime}).ExecuteCommand()
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public int UpdateIgnoreColumns<T>(T t, out string msg, Expression<Func<T, object>> columns) where T : class, new()
        {
            return this.DoTask<int>(out msg, () =>
            {
                return this.freeSql.Update<T>(t).IgnoreColumns(columns).ExecuteAffrows();
            }, true);
        }

        /// <summary>
        /// 只更新某列--按需更新
        /// this.sugarClient.UpdateColumns(it => new { it.Name, it.CreateTime }).ExecuteCommand()
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <param name="columns"></param>
        /// <returns></returns>
        public int UpdateColumns<T>(T t, out string msg, Expression<Func<T, object>> columns) where T : class, new()
        {
            return this.DoTask<int>(out msg, () =>
            {
                return this.freeSql.Update<T>(t).UpdateColumns(columns).ExecuteAffrows();
            }, true);
        }

        /// <summary>
        /// 更新忽略null并且忽略默认值 (比如int默认值是0就不更新)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <param name="ignoreAllNullColumns"></param>
        /// <param name="isOffIdentity"></param>
        /// <param name="ignoreAllDefaultValue"></param>
        /// <returns></returns>
        public int UpdateIgnoreColumns<T>(T t, out string msg, bool ignoreAllNullColumns, bool isOffIdentity = false, bool ignoreAllDefaultValue = false) where T : class, new()
        {
            return this.DoTask<int>(out msg, () =>
            {
                return this.freeSql.Update<T>().SetSourceIgnore(t, col => col == null).ExecuteAffrows();
            }, true);
        }

        /// <summary>
        /// 条件更新
        /// this.sugarClient.Updateable(studentUp).Where(it => it.Id == 7003783).ExecuteCommand()
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <param name="expression"></param>
        /// <returns></returns>
        public int UpdateWhere<T>(T t, out string msg, Expression<Func<T, bool>> expression) where T : class, new()
        {
            return this.DoTask<int>(out msg, () =>
            {
                return this.freeSql.Update<T>().SetSource(t).Where(expression).ExecuteAffrows();
            }, true);
        }

        /// <summary>
        /// 修改实体
        /// </summary>
        /// <typeparam name="int"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int Update<T>(T t, out string msg) where T : class, new()
        {
            return this.DoTask<int>(out msg, () =>
            {
                IBaseRepository<T> repo = this.freeSql.GetRepository<T>();
                return repo.Update(t); //对比快照时的变化
            }, true);
        }

        /// <summary>
        /// 批量修改
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public int UpdateBatch<T>(List<T> list, out string msg) where T : class, new()
        {
            return this.DoTask<int>(out msg, () =>
            {
                return this.freeSql.Update<T>()
                .SetSource(list)
                .ExecuteAffrows();
            }, true);
        }

        #endregion

        #region 删除
        /// <summary>
        /// 根据字典集合删除
        /// </summary>
        /// <param name="columns"></param>
        /// <param name="msg"></param>
        /// <param name="aliasname"></param>
        /// <returns></returns>
        public bool DeleteDictionary(List<Dictionary<string, object>> columns, out string msg, string aliasname)
        {
            return this.DoTask<bool>(out msg, () =>
            {
                return this.freeSql.DeleteDict(columns).AsTable(aliasname).ExecuteAffrows() > 0;
            }, true);
        }

        /// <summary>
        /// 删除指定主键集合数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="msg"></param>
        /// <param name="ids"></param>
        /// <returns></returns>
        public bool Delete<T>(out string msg, long[] ids) where T : BaseModel<long>, new()
        {
            return this.DoTask<bool>(out msg, () =>
            {
                return this.freeSql.Delete<T>(ids).ExecuteAffrows() > 0;
            }, true);
        }

        /// <summary>
        /// 根据ID删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="id"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool Delete<T>(int id, out string msg) where T : BaseModel<long>, new()
        {
            return this.DoTask<bool>(out msg, () =>
            {
                return this.freeSql.Delete<T>().Where(it => it.Id == id).ExecuteAffrows() > 0;
            }, true);
        }

        /// <summary>
        /// 根据条件删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="where"></param>

        /// <param name="msg"></param>
        /// <returns></returns>
        public bool Delete<T>(Expression<Func<T, bool>> where, out string msg) where T : class, new()
        {
            return this.DoTask<bool>(out msg, () =>
            {
                return this.freeSql.Delete<T>().Where(where).ExecuteAffrows() > 0;
            }, true);
        }

        /// <summary>
        /// 根据集合删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool Delete<T>(List<T> t, out string msg) where T : BaseModel<long>, new()
        {
            return this.DoTask<bool>(out msg, () =>
            {
                return this.freeSql.Delete<T>(t).ExecuteAffrows() > 0;
            }, true);
        }

        /// <summary>
        /// 根据条件删除
        /// this.freeSql.Delete<Company>(new Company { Id = company.Id }).ExecuteAffrows();
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dywhere"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool Delete<T>(object dywhere, out string msg) where T : BaseModel<long>, new()
        {
            return this.DoTask<bool>(out msg, () =>
            {
                return this.freeSql.Delete<T>(dywhere).ExecuteAffrows() > 0;
            }, true);
        }

        #endregion

        #region 执行SQL
        /// <summary>
        /// 执行SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="msg"></param>
        /// <param name="parameters"></param>
        /// var parameters = new List<SugarParameter>(){
        /// new SugarParameter("@id",30) };
        /// <returns></returns>
        public bool ExecuteSql(string sql, out string msg, object parameters)
        {
            return this.DoTask<bool>(out msg, () =>
            {
                var data = this.freeSql.Ado.ExecuteNonQuery(sql, parameters);
                return data > -1;
            }, true);
        }

        /// <summary>
        /// 执行SQL
        /// </summary>
        /// <param name="sql"></param>
        /// <param name="parameters"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public bool ExecuteSql(string sql, object parameters, out string msg)
        {
            return this.DoTask<bool>(out msg, () =>
            {
                var data = this.freeSql.Ado.ExecuteNonQuery(sql, parameters);
                return data > -1;
            }, true);

        }
        #endregion

        #region 外部执行具体操作
        /// <summary>
        /// 外部执行具体操作
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="action"></param>
        /// <param name="istran"></param>
        public void Work(out string msg, Action<IFreeSql> action, bool istran = false)
        {
            msg = string.Empty;
            if (istran)
            {
                using (var com = this.freeSql.CreateUnitOfWork())
                {
                    try
                    {
                        com.GetOrBeginTransaction();
                        action.Invoke(this.freeSql);
                        com.Commit();
                    }
                    catch (Exception ex)
                    {
                        msg = ex.Message;
                        if (ex.InnerException != null)
                        {
                            msg += "," + ex.InnerException.Message;
                        }
                        com.Rollback();
                    }

                }
            }
            else
            {
                try
                {
                    action.Invoke(this.freeSql);
                }
                catch (Exception ex)
                {
                    msg = ex.Message;
                    if (ex.InnerException != null)
                    {
                        msg += "," + ex.InnerException.Message;
                    }
                }
            }
        }
        #endregion
    }
}
